﻿using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Services;
using YAKEJI.Abp.Domain.Repositories;
using YAPACS.BusinessObjects.Exams;
using YAPACS.BusinessObjects.Managements.Exams;
using YAPACS.RisServer.Abstractions;

namespace YAPACS.RisServer.Services;

public class CallQueuingService(
    IRepository<CallingQueuing, Guid> callingQueuingRepository,
    IRepository<CallingTemplate, Guid> callingTemplateRepository
    ) : DomainService, ICallQueuingService, ITransientDependency
{
    private readonly IRepository<CallingQueuing, Guid> _callingQueuingRepository = callingQueuingRepository;
    private readonly IRepository<CallingTemplate, Guid> _callingTemplateRepository = callingTemplateRepository;

    public async Task AddCallQueuingAsync(ExamQueuing examQueuing)
    {
        var callingTemplate = await _callingTemplateRepository.FirstOrDefaultAsync(t => t.Department == examQueuing.Device.Station.Room.Department);
        var callingTimes = callingTemplate != null ? callingTemplate.CallingTimes : 3;
        callingTimes = Math.Max(1, callingTimes);

        var callingContent = "请 [呼叫编号]号 [患者姓名] 到 [检查诊室] 检查";
        if (!string.IsNullOrWhiteSpace(callingTemplate?.Template))
        {
            callingContent = callingTemplate.Template;
        }

        callingContent = callingContent.Replace("[呼叫编号]", examQueuing.CallNumber);
        callingContent = callingContent.Replace("[患者姓名]", examQueuing.Exam.Patient.Name);
        callingContent = callingContent.Replace("[检查诊室]", examQueuing.Device.Station.Room.GetShortName());

        var callQueuing = await _callingQueuingRepository.NewEntityAsync();
        callQueuing.ExamQueuing = examQueuing;
        callQueuing.CallingContent = callingContent;
        callQueuing.CallingTimes = callingTimes;
    }

    public async Task<IList<CallingQueuing>> GetCallQueuingListAsync(Guid departmentId)
    {
        return await _callingQueuingRepository.GetListAsync(q => q.ExamQueuing.Device.Station.Room.Department.Id == departmentId);
    }

    public async Task RemoveCallQueuingAsync(CallingQueuing callingQueuing)
    {
        await _callingQueuingRepository.DeleteAsync(callingQueuing);
    }
}
